package model.fshare.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import model.roomManagement.Implementation.Server;
import model.roomManagement.Interface.IDBC;

public class FReceivingSocketDistributor extends FShareSocketDistributor
{
	private static FReceivingSocketDistributor instance = null;
	
	private FReceivingSocketDistributor() 
	{
		try 
		{
			serverSocket = new ServerSocket( 5998 );
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}

	@Override
	public void run() 
	{
		System.out.println( "====== FReceivingSocketDistributor: Start Running! =====" );
		
		while( true )
		{
			try
			{
				Socket socket = serverSocket.accept();
				dealRequest( socket );
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			
		}
	}

	
	private void dealRequest(Socket socket)
	{
		try 
		{
			BufferedReader requestReader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
			int roomId = Integer.parseInt( requestReader.readLine() );
			int updaterId = Integer.parseInt( requestReader.readLine() );
			String fileName = requestReader.readLine();
			
			System.out.println( "======== File Upload: " + new String( fileName.getBytes(), "GBK" ) );
			// Check if the file exist
			// Call server service
			// db   File getFile(fileName fileRoom)
			IDBC idbc = Server.getDB();
			File dbRecord = idbc.getFile( fileName, roomId );
			
			ObjectOutputStream responseWriter = new ObjectOutputStream( socket.getOutputStream() );
			if ( dbRecord == null )
			{
				responseWriter.writeObject( true );
				distribute( socket, roomId, updaterId, fileName );
			}
			else
			{
				responseWriter.writeObject( false );
				responseWriter.close();
			}

		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	public static FReceivingSocketDistributor getInstance()
	{
		if ( instance == null )
		{
			instance = new FReceivingSocketDistributor();
		}
		
		return instance;
	}

	@Override
	protected void distribute(Socket socket, int roomId,
							  int userId, String fileName)
	{
		FileReceiver fReceiver = new FileReceiver( socket, roomId, userId, fileName );
		Thread fReceivingThread = new Thread( fReceiver );
		fReceivingThread.start();
	}
	

}
